package com.tianci.appstore.ui.list.cgylist;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.skyworth.framework.skysdk.ipc.SkyStartActivity;
import com.tianci.appstore.AppListActivity;
import com.tianci.appstore.R;
import com.tianci.appstore.audio.IAudio;
import com.tianci.appstore.controller.AppStoreAppListController;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppStatus;
import com.tianci.appstore.ui.data.SkyCategoryData;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.list.ListBaseView;
import com.tianci.appstore.ui.list.ListFlipper;
import com.tianci.appstore.ui.list.SkyListAdapter;
import com.tianci.appstore.ui.util.UICommon;
import com.tianci.appstore.ui.widget.LeftImageButtonLayer;
import com.tianci.appstore.ui.widget.LeftImageButtonLayer.OnLayerFocusChangeListener;
import com.tianci.appstore.ui.widget.SkyAppPager.Direction;
import com.tianci.appstore.ui.widget.SkyCategoryBar.OnCategoryClickListener;
import com.tianci.appstore.ui.widget.SkyCustomLayout;
import com.tianci.appstore.ui.widget.SkyCustomLayout.BlockData;
import com.tianci.appstore.ui.widget.SkyCustomLayout.CustomLayoutParams;
import com.tianci.appstore.utils.SkyConstants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AppListView extends ListBaseView implements OnCategoryClickListener,
        CgyListDataListener, OnLayerFocusChangeListener {
    protected Context mContext;

    //    protected ListHeadLayout headLayout;
    private int crtCgyIndex = 0;
    private int[] crtPageIndexes;
    protected SkyCategoryClickBar cgyBar;
    protected ListFlipper listFlipper;
    protected TextView pageNumberText;
    protected ImageView leftArrow, rightArrow;

    protected ListOperationController mController;
    private String crtCgyId;
    private LeftImageButtonLayer mButtonLayer = null;

    boolean inSelectionMode = false;
    boolean isEmptyPage = true;

    public AppListView(Context context, String cgyId) {
        super(context);
        this.mContext = context;
        this.crtCgyId = cgyId;
        AppStoreAppListController.getInstance().init();
        AppStoreAppListController.getInstance().setListDataListener(this);
        AppStoreAppListController.getInstance().getRelationCategory(cgyId);
        // TODO Auto-generated constructor stub
        setLoadingVisible(true);
        createView();
//        isEmptyPage = true;
    }

    private void createView() {
        SkinManager.setBackground(this, R.drawable.ui_sdk_app_bg);
        // 新建一个HeadLayout
        initTitleBar();
        addButtonsLayer();
        initFlipper();
        initPageText();
        mController.setButtonLayer(mButtonLayer);
        mController.setCategoryBar(cgyBar);
    }

    private void initTitleBar() {
//        ImageView dividerImage = new ImageView(mContext);
//        SkinManager.setBackground(dividerImage, R.drawable.pic_line);
//        LayoutParams dividerParams = new LayoutParams(
//                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
//        dividerParams.setMargins(0, SkyConstants.Div(97), 0, 0);
//        this.addView(dividerImage, dividerParams);

        cgyBar = new SkyCategoryClickBar(mContext);
        LayoutParams params = new LayoutParams(SkyConstants.Div(1400), SkyConstants.Div(200));
        params.setMargins(SkyConstants.Div(102), SkyConstants.Div(85), 0, 0);
        this.addView(cgyBar, params);

        cgyBar.setCategoryClickListener(this);

    }

    private void addButtonsLayer() {
        mButtonLayer = new LeftImageButtonLayer(mContext);
        mButtonLayer.setLayerFocusChangeListener(this);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.RIGHT);
        params.setMargins(0, SkyConstants.Div(85), SkyConstants.Div(115), 0);
        mButtonLayer.setLayoutParams(params);
        mButtonLayer.initDefaultParams();
        this.addView(mButtonLayer);
    }

    private void initFlipper() {
        int row = 3, column = 4;
        listFlipper = new ListFlipper(mContext, Direction.HORIZONTAL);
        mController = new ListOperationController(mContext, listFlipper, row, column);
        List<BlockData> blockDataList = createListBlockData(row, column);
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT; i++) {
            SkyCustomLayout page = new SkyCustomLayout(mContext, CoocaaApplication.mDiv);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            page.setLayoutParams(params);
            CustomLayoutParams netAppParams = new CustomLayoutParams();
            netAppParams.mRow = row;
            netAppParams.mCol = column;
            netAppParams.mBlockWidth = SkyConstants.Div(472);
            netAppParams.mBlockHeight = SkyConstants.Div(280);
            netAppParams.mHorizontalSpace = SkyConstants.Div(-47);
            netAppParams.mVerticalSpace = SkyConstants.Div(-36);
            netAppParams.mMarginTop = SkyConstants.Div(188);
            page.setCustomLayoutParams(netAppParams);
            page.setBlockDatas(blockDataList);
            SkyListAdapter mAdapter = new SkyListAdapter(mContext, ListType.CGY_APP_LIST, i, CoocaaApplication.mDiv);
            mAdapter.setKeyListener(mController);
            mAdapter.setMultiSelectListener(mController);
            mAdapter.setOnItemClickListener(mController);
            page.setAdapter(mAdapter);
            listFlipper.addView(page);
        }
        contentLayout.addView(listFlipper, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, Gravity.CENTER));
    }

    private List<BlockData> createListBlockData(int row, int column) {
        List<BlockData> datas = new ArrayList<BlockData>();
        for (int i = 0; i < row * column; i++) {
            BlockData data = new BlockData();
            data.mColNum = 1;
            data.mRowNum = 1;
            data.mBlock = new int[]{i};
            boolean leftTurn = false;
            boolean rightTurn = false;
            if (i % column == 0)
                leftTurn = true;
            if (i % column == column - 1)
                rightTurn = true;
            data.mTurnPage = new boolean[]{leftTurn, false, rightTurn, false};
            datas.add(data);
        }
        return datas;
    }

    private void initPageText() {
        leftArrow = new ImageView(mContext);
        rightArrow = new ImageView(mContext);
        leftArrow.setImageDrawable(SkinManager.getResDrawable(R.drawable.left_arrow));
        rightArrow.setImageDrawable(SkinManager.getResDrawable(R.drawable.right_arrow));
        LayoutParams leftParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT);
        LayoutParams rightParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT);
        leftParams.leftMargin = SkyConstants.Div(36);
        rightParams.rightMargin = SkyConstants.Div(36);

        contentLayout.addView(leftArrow, leftParams);
        contentLayout.addView(rightArrow, rightParams);

        pageNumberText = UICommon.newTextView(mContext, SkyConstants.Dpi(33), R.color.pageNumberColor);
        LayoutParams pageParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        pageParams.bottomMargin = SkyConstants.Div(45);
        contentLayout.addView(pageNumberText, pageParams);
        mController.setPageNoView(pageNumberText, leftArrow, rightArrow);
    }

    public void setFocusCgyIndex(int index) {
        cgyBar.setFocusPos(index);
    }

    @Override
    public void categoryClicked(SkyCategoryData data, int cgyIndex) {
        // TODO Auto-generated method stub
        if (crtCgyIndex == cgyIndex)
            return;
        crtPageIndexes[crtCgyIndex] = mController.getCurrentPageIndex();
        int pageIndex = crtPageIndexes[cgyIndex];
        if (crtCgyIndex < cgyIndex) {
            crtCgyIndex = cgyIndex;
            mController.setCategoryData(data, pageIndex, false);
        }
        if (crtCgyIndex > cgyIndex) {
            crtCgyIndex = cgyIndex;
            mController.setCategoryData(data, pageIndex, true);
        }

        if(mContext instanceof AppListActivity){
            SkyStartActivity.onPageClose((AppListActivity)mContext);
            HashMap<String,String> map = new HashMap<String,String>();
            map.put("app_list_id",data.id);
            SkyStartActivity.onPageOpen((AppListActivity)mContext, map);
        }
        setLoadingVisible(true);
    }

    @Override
    public void onCategoryLoaded(String parentTitle, List<SkyCategoryData> cgyList) {
        // TODO Auto-generated method stub
        if (cgyList != null)
            LogUtils.d("list", "On Category Loaded, parentTitle = " + parentTitle + ", cgy count = " + cgyList.size());
        else
            LogUtils.d("list", "On Category Loaded, parentTitle = " + parentTitle + ", cgyList == null");
        Message msg = uiHandler.obtainMessage(UPDATE_CGY);
        msg.obj = cgyList;
        uiHandler.sendMessage(msg);
    }

    @Override
    public void onAppPageLoaded(String cgyId, int pageIndex, List<SkyListAppData> appList) {
        // TODO Auto-generated method stub
        if (appList != null)
            LogUtils.d("list", "On AppPage Loaded, cgyId = " + cgyId + ", pageIndex = " + pageIndex + ", app count = " + appList.size());
        else
            LogUtils.d("list", "On AppPage Loaded, cgyId = " + cgyId + ", pageIndex = " + pageIndex + ", appList == null");

        if (cgyBar.getCurrentClickedData() == null)
            return;
        if (!cgyId.equals(cgyBar.getCurrentClickedData().id)) {
            LogUtils.d("list", "AppListView, onAppPageLoaded -- Category Id doesn't match, return !!!!!" + cgyId + " " + cgyBar.getCurrentClickedData().id);
            return;
        }
        Message msg = uiHandler.obtainMessage(UPDATE_LIST_PAGE);
        msg.arg1 = pageIndex - 1;   // 后台index从1开始，本地页码从0开始
        msg.obj = appList;
        uiHandler.sendMessage(msg);
    }

    @Override
    public void onAppStatusChanged(String pkgName, AppStatus status) {
        // TODO Auto-generated method stub
        Message msg = uiHandler.obtainMessage(UPDATE_APP_STATUS);
        Bundle bundle = new Bundle();
        bundle.putString("pkgName", pkgName);
        msg.setData(bundle);
        msg.obj = status;
        uiHandler.sendMessage(msg);
    }

    private void refreshCategory(List<SkyCategoryData> cgyDataList) {
        if (cgyDataList == null || cgyDataList.size() == 0) {
            setEmptyTipVisible(true, mContext.getString(R.string.no_app_list));
            return;
        }
//        setEmptyTipVisible(false, null);
        cgyBar.setCategoryDatas(cgyDataList);
        crtCgyIndex = 0;
        crtPageIndexes = new int[cgyDataList.size()];
        for (int i = 0; i < cgyDataList.size(); i++) {
            SkyCategoryData cgyData = cgyDataList.get(i);
            if (crtCgyId.equals(cgyData.id)) {
                crtCgyIndex = i;
                break;
            }
        }

        // ///////////////////////////////////////////////////////request crtPageData
        cgyBar.setFocusPos(crtCgyIndex);
        cgyBar.setClickedPos(crtCgyIndex);
//        cgyBar.hideFocusCursor();
        mController.setCategoryData(cgyDataList.get(crtCgyIndex), 0);
        mController.setCategoryDatas(cgyDataList);

        SkyCustomLayout child = (SkyCustomLayout) listFlipper.getCurrentView();
        child.setFocusPos(0, true);
//        isEmptyPage = true;
    }

    protected static final int UPDATE_CGY = 0;
    protected static final int UPDATE_LIST_PAGE = 1;
    protected static final int UPDATE_APP_STATUS = 2;
    private Handler uiHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case UPDATE_CGY:
                    refreshCategory((List<SkyCategoryData>) msg.obj);
                    break;
                case UPDATE_LIST_PAGE:
                    if (msg.arg1 == mController.getCurrentPageIndex())
                        setLoadingVisible(false);
                    if (msg.arg1 < 0 && msg.obj == null) {
                        setEmptyTipVisible(true, mContext.getString(R.string.request_data_timeout));
                        return;
                    }
                    mController.refreshPage(msg.arg1, (List<SkyListAppData>) msg.obj);
                    if (isEmptyPage) {
                        SkyCustomLayout page = (SkyCustomLayout) listFlipper.getCurrentView();
                        cgyBar.hideFocusCursor();
                        page.setFocusPos(0, true);
                        isEmptyPage = false;
                    }
                    setEmptyTipVisible(false, null);
                    break;
                case UPDATE_APP_STATUS:
                    mController.updateAppStatus(msg.getData().getString("pkgName"), (AppStatus) msg.obj);
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void destroyController() {
        // TODO Auto-generated method stub
        AppStoreAppListController.getInstance().destroy();
        if (cgyBar != null)
            cgyBar.onDestory();
        if (mButtonLayer != null)
            mButtonLayer.onDestory();
        try {
            if (listFlipper != null) {
                int count = listFlipper.getChildCount();
                for (int i = 0; i < count; i++) {
                    getPageByIndex(i).getAdapter().destory();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private SkyCustomLayout getPageByIndex(int index) {
        return (SkyCustomLayout) listFlipper.getChildAt(index);
    }

    @Override
    public void onFocusChange(View leaveView, int leaveIndex, int leaveKey) {
        // TODO Auto-generated method stub
        if (crtPageIndexes == null)
            return;
        if (leaveIndex == 0 && leaveKey == KeyEvent.KEYCODE_DPAD_LEFT) {
            cgyBar.setFocusPos(crtPageIndexes.length - 1);
        }
    }

    @Override
    public void resume() {
        // TODO Auto-generated method stub

    }

    @Override
    public IAudio getAudioInterface() {
        // TODO Auto-generated method stub
        return mController;
    }
}
